
package com.thb.pay.core.interceptor;

import com.thb.pay.core.annotation.AsyncRequestRequired;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 方法 异步拦截器
 */
@Slf4j
@Component
public class AsyncMethodAspect {

    private ExecutorService executor = Executors.newFixedThreadPool(15);

    public static AsyncRequestRequired getRequired(ProceedingJoinPoint joinPoint) throws Exception {
        Signature sig = joinPoint.getSignature();
        Method m = joinPoint.getTarget().getClass().getMethod(joinPoint.getSignature().getName(), ((MethodSignature) sig).getParameterTypes());
        AsyncRequestRequired required = m.getAnnotation(AsyncRequestRequired.class);
        return required;
    }

    /**
     * 切点
     */
    @Pointcut("@annotation(com.thb.pay.core.annotation.AsyncRequestRequired)")
    public void asyncMethodPointcut() {

    }

    @Around("asyncMethodPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        AsyncRequestRequired requestRequired = getRequired(point);
        if (requestRequired != null) {
            executor.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return null;
                }
            });
        }
        Object result = point.proceed();
        return result;
    }
}
